package com.java.cart.controller;

import com.java.cart.service.CartService;
import com.java.param.CartListParam;
import com.java.param.ProductIdRemoveParam;
import com.java.pojo.Cart;
import com.java.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/cart")
public class CartController {
    @Autowired
    private CartService cartService;

    @PostMapping("/save")
    public R save(@RequestBody Cart cart){
        return cartService.save(cart);
    }

    @PostMapping("/list")
    public R list(@RequestBody @Validated CartListParam cartListParam, BindingResult result){
        if(result.hasErrors()){
            return R.fail("参数错误，无法查看购物车详情！");
        }
        return cartService.list(cartListParam);
    }
    @PostMapping("/update")
    public R update(@RequestBody Cart cart){
        return cartService.update(cart);
    }
    @PostMapping("/remove")
    public R remove(@RequestBody Cart cart){
        return cartService.remove(cart);
    }

    /**
     * 根据商品id检查所有用户购物车是否有该商品
     * @param productIdRemoveParam
     * @return
     */
    @PostMapping("/product/check")
    public R check(@RequestBody @Validated ProductIdRemoveParam productIdRemoveParam,BindingResult result){
        if(result.hasErrors()){
            return R.fail("商品id为空，不可删除！");
        }
        return cartService.check(productIdRemoveParam);
    }
}
